<template>
  <!-- 获取验证码倒计时 -->
  <div
    v-if="showGetting"
    class="flex-box blue-bg white h30 radius15 fs26 minw70 box-b disib curPer"
    @click="getCode">
    <div class="fs12 fColorf45 w100 h30 flex-box"
         v-if="!smsGetting">发送验证码</div>
    <div class="fs12 w100 h30 flex-box white fw500" v-else>
      {{ countDown }}s
    </div>
  </div>
</template>

<script>
import {mapGetters} from "vuex";

export default {
  name: "code-item",
  props: {
    showGetting: {
      type: Boolean,
      default: false
    },
    info: {
      type: Object,
      default() {
        return {};
      }
    },
    // 验证码接口 1:忘记密码邮箱验证码
    sendType: {
      type: Number,
      default: 1
    },
  },
  data() {
    return {
      countDown: 120,
      smsGetting:false,
      allowGetCode: true,
      timer:null,
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    async getCode() {
      const vm = this;
      if(!this.allowGetCode) return;

      let params = {}
      if (!this.info.userName) {
        vm.$message.error('请输入用户名')
        return
      }

      if (!this.info.email) {
        vm.showMessageMin({
          message: '请输入邮箱',
          type:'error',
        })
        return
      }

      params = {
        ...this.info,
        userId: vm.userInfo.userId
      }

      this.allowGetCode = false;
      let request = null;
      if(vm.sendType == 1){
        request = vm.apiUrl.sendEmailCode(params, 'POST')
      }
      // else if(vm.sendType == 2){
      //   request = vm.apiUrl.sendSmsCode(params, 'POST')
      // }else{
      //   request = vm.apiUrl.sendPwdSmsCode(params, 'POST')
      // }
      request.then(res=>{
        const { code,msg } = res;
        if (code != 0) {
          vm.smsGetting = false;
          vm.$message.error(msg);
        }else{
          vm.smsGetting = true
          vm.timer = setInterval(()=>{
            vm.countDown--
            if(vm.countDown===0){
              vm.smsGetting = false;
              vm.countDown = 120;
              clearInterval(vm.timer)
            }
          },1000)
          // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
          vm.$once('hook:beforeDestroy', () => {
            clearInterval(vm.timer);
          })
        }
      }).finally(() => {
        setTimeout(() => {
          vm.allowGetCode = true;
        },1500)
      })
    },
  }
}
</script>

<style lang="less" scoped>

</style>
